package sjg.DataStructures.stack;

import java.util.Scanner;

public class ArrayStackDemo {

    public static void main(String[] args) {
        // 测试
        ArrayStack stack = new ArrayStack(4);
        boolean loop = true; // 判断是否退出菜单
        Scanner scanner = new Scanner(System.in);
        String key = "";
        while (loop) {
            System.out.println("show: 显示栈");
            System.out.println("exit: 退出程序");
            System.out.println("push: 入栈");
            System.out.println("pop: 出栈");
            System.out.println("请输入你要执行的操作~");
            key = scanner.next();
            switch (key) {
                case "show":
                    stack.list();
                    break;
                case "exit":
                    loop = false;
                    break;
                case "push":
                    System.out.print("请输入一个数：");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    int pop = stack.pop();
                    System.out.println("出栈数据为：" + pop);
                    break;
            }
        }
    }
}


// 定义一个ArrayStack 表示栈
class ArrayStack {
    private int maxSize; // 表示栈大小
    private int[] stack; // 数组，模拟栈
    private int top = -1; //top表示栈顶，初始化为 -1

    // 构造器
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }

    // 判断占满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    // 判断栈空
    public boolean isEmpty() {
        return top == -1;
    }

    // 入栈
    public void push(int val) {
        // 判断栈满
        if (isFull()) {
            System.out.println("栈满~~");
            return;
        }
        top++;
        stack[top] = val;
    }

    // 出栈
    public int pop() {
        // 判断栈空
        if (isEmpty()) {
            System.out.println("栈空~~");
            throw new RuntimeException("栈空~");
        }
        top--;
        return stack[top + 1];
    }

    //遍历栈
    public void list() {
        // 遍历数组
        for (int i = 0; i <= top; i++) {
            System.out.println(stack[i]);
        }
    }

}